﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using BasicForms;
using Lists;
using GeneralLibs;

namespace ReportGenerators.QuanLyKho.ThongKeTonTheoNhaCungCap
{
    public partial class FrmTongHopTienHangTheoNhaCungCap : BasicForms.FrmSupportPrintableComponents
    {
        public FrmTongHopTienHangTheoNhaCungCap()
        {
            InitializeComponent();
        }

        private void FrmThongKeNhapXuatTon_Load(object sender, EventArgs e)
        {
            if (DesignMode) return;
            try
            {
                cmbKho.DataSource = DanhMucKho.Instance.DataView;
                cmbKho.DisplayColumn = "Ten";
                cmbKho.ValueColumn = "ID";
                cmbKho.AddVisibleColumn("Ma", "Mã");
                cmbKho.AddVisibleColumn("Ten", "Tên");
                cmbKho.EditValue = Guid.Empty;

                dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Merge(DanhMucDoiTuongNghiepVu.Instance.DataView.ToTable());
                gridControlDsDoiTac.DataSource = dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu;

                chkChooseAllDoiTac.Checked = true;

                cmbKyBaoCao.SelectedIndex = 19;
                rdoGiaVonConTrongKho.Checked = false;
                rdoGiaVonMuaVao.Checked = true;
            }
            catch (Exception ex)
            {
            }

            try
            {
                foreach (DevExpress.XtraGrid.Columns.GridColumn column in gridViewDsDoiTac.Columns)
                {
                    column.OptionsFilter.AutoFilterCondition = DevExpress.XtraGrid.Columns.AutoFilterCondition.Contains;
                }

                chkChooseAllDoiTac.Checked = false;
                FormatNumberInGridView(gridViewDsDoiTac);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkChooseAllDoiTac_CheckedChanged(object sender, EventArgs e)
        {
            foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
            {
                row["Choose"] = chkChooseAllDoiTac.Checked;
            }
        }

        private void cmbKho_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete) cmbKho.EditValue = Guid.Empty;
        }

        private DataTable GetHangDaCoGiaoDich(SqlCommand cmd, Guid selectedKhoID, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM NhatKyKho \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM TonKho \n " +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID \n" +
                                                   "FROM NhatKyKho \n" +
                                                   "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL \n" +
                                                   "UNION \n" +
                                                   "SELECT DISTINCT VatTuHangHoaID  \n" +
                                                   "FROM TonKho  \n" +
                                                   "WHERE SoLuong <> 0 \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }
        //lấy ra những hàng đã có giao dịch và mua của nhà cung cấp cụ thể
        private DataTable GetHangDaCoGiaoDichMuaCuaNCC(SqlCommand cmd, Guid selectedKhoID, List<Guid> nhaCungCapIDs ,DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM NhatKyKho \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM TonKho \n " +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID \n" +
                                                   "FROM NhatKyKho \n" +
                                                   "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL \n" +
                                                   "UNION \n" +
                                                   "SELECT DISTINCT VatTuHangHoaID  \n" +
                                                   "FROM TonKho  \n" +
                                                   "WHERE SoLuong <> 0 \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }

        private DataTable GetToanBoHangDangSuDung(SqlCommand cmd, Guid selectedKhoID, DateTime ngayKetThuc)
        {
            try
            {
                ThoiDiemKhoaSo thoiDiemKhoaSo = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemChotSoDuGanNhat(ngayKetThuc);
                if (selectedKhoID != null && selectedKhoID != Guid.Empty)
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM NhatKyKho \n" +
                                                    "WHERE  KhoID = @KhoID AND @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi \n" +
                                                    "   AND VatTuHangHoaID is not null  \n" +
                                                    "UNION \n" +
                                                    "SELECT DISTINCT VatTuHangHoaID, KhoID \n" +
                                                    "FROM TonKho \n " +
                                                    "WHERE KhoID = @KhoID AND SoLuong <> 0 \n" +
                                                    "   AND VatTuHangHoaID is NOT NULL");
                    cmd.Parameters.Clear();
                    cmd.Parameters.AddWithValue("KhoID", selectedKhoID);
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                else
                {
                    cmd.CommandText = string.Format("SELECT DISTINCT VatTuHangHoaID \n" +
                                                   "FROM NhatKyKho \n" +
                                                   "WHERE  @ThoiDiemDau <= Ngay AND Ngay <= @ThoiDiemCuoi  \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL \n" +
                                                   "UNION \n" +
                                                   "SELECT DISTINCT VatTuHangHoaID  \n" +
                                                   "FROM TonKho  \n" +
                                                   "WHERE SoLuong <> 0 \n" +
                                                   "	AND VatTuHangHoaID is NOT NULL ");

                    cmd.Parameters.Clear();
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("ThoiDiemDau", thoiDiemKhoaSo.ThoiDiem);
                    cmd.Parameters.AddWithValue("ThoiDiemCuoi", ngayKetThuc);
                }
                DataTable dtDaCoGiaoDich = new DataTable();
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                da.Fill(dtDaCoGiaoDich);
                return dtDaCoGiaoDich;
            }
            catch (Exception ex)
            {
                string message = string.Format("Lỗi [{0}] ở \n {1}", ex.Message, ex.StackTrace.Substring(0, ex.StackTrace.IndexOf("\n")));
                throw new CustomException(message);
                return null;
            }
        }

        private void btnLoad_Click(object sender, EventArgs e)
        {
            DateTime ngayBatDau = dtNgayBatDau.DateTime;
            DateTime ngayKetThuc = dtNgayKetThuc.DateTime;
            if (!(FrmThamSoBaoCao.CheckKyBaoCaoVaThoiDiemKhoaSo(dtNgayBatDau, dtNgayKetThuc))) return;
            ThoiDiemKhoaSo thoiDiemKhoaSoGanNhat = DanhMucThoiDiemKhoaSo.Instance.GetThoiDiemKhoaSoGanNhat(ngayKetThuc);

            Guid selectedKhoID = Guid.Empty;
            if (cmbKho.EditValue is Guid && (Guid)cmbKho.EditValue != Guid.Empty)
                selectedKhoID = (Guid)cmbKho.EditValue;

            BasicForms.FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(GeneralLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand(); cmd.CommandTimeout = Config.TimeOut;

                DataTable dtDaCoGiaoDich = new DataTable();
                //Nếu option chỉ chon những hàng đã giao dịch thì chỉ get những hàng đã có giao dịch
                if (chkShowHangDaCoGiaoDich.Checked)
                    dtDaCoGiaoDich = GetHangDaCoGiaoDich(cmd, selectedKhoID, ngayKetThuc);
                else //Nếu không thì lấy toàn bộ danh mục
                    dtDaCoGiaoDich = DanhMucVatTuHangHoa.Instance.DataTable;

                dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Clear();
                dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Clear();

                int count = 0;
                int total = dtDaCoGiaoDich.Rows.Count;

                foreach (DataRow row in dtDaCoGiaoDich.Rows)
                {
                    BasicForms.FrmProgressBar.Status = string.Format("Đang xử lý {0}/{1}", count, dtDaCoGiaoDich.Rows.Count);
                    count++;

                    Guid vatTuHangHoaID;
                    if (chkShowHangDaCoGiaoDich.Checked)
                        vatTuHangHoaID = (Guid)row["VatTuHangHoaID"];
                    else
                        vatTuHangHoaID = (Guid)row["ID"];

                    VatTuHangHoa vatTuHangHoa = DanhMucVatTuHangHoa.Instance.GetByID(vatTuHangHoaID);
                    if (vatTuHangHoa == null) continue;
                    TonKho tonKho = new TonKho();
                    decimal donGiaVon = 0;

                    //Lấy giá vốn trung bình còn lại trong kho
                    if (selectedKhoID == Guid.Empty)
                    {
                        tonKho = TonKho.CalculateTongTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVao(cmd, ngayKetThuc, vatTuHangHoaID);
                        if (tonKho.SoLuong > 0)
                        {
                            if (rdoGiaVonConTrongKho.Checked)
                                donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                            else if (rdoGiaVonMuaVao.Checked)
                                donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonNhapTrungBinhToanBoCacKhoByID(vatTuHangHoa.ID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                        }
                    }
                    else
                    {
                        tonKho = TonKho.CalculateTonTuThoiDiemKhoaSoGanNhatDenThoiDiemNhapVaoTheoKho(cmd, ngayKetThuc, selectedKhoID, vatTuHangHoaID);
                        if (tonKho.SoLuong > 0)
                        {
                            if (rdoGiaVonConTrongKho.Checked)
                                donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonTrungBinhTheoGiaTriConLaiToanBoTheoKhoByID(vatTuHangHoa.ID, selectedKhoID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                            else
                                donGiaVon = (decimal)DanhMucVatTuHangHoa.Instance.GetGiaVonNhapTrungBinhToanBoTheoKhoByID(vatTuHangHoa.ID, selectedKhoID, thoiDiemKhoaSoGanNhat.ID, ngayBatDau, ngayKetThuc);
                        }
                    }

                    DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.NewRow();
                    addedRow["Ma"] = vatTuHangHoa.Ma;
                    addedRow["Ten"] = vatTuHangHoa.Ten;
                    if (vatTuHangHoa.DoiTuongNghiepVu != null)
                        addedRow["DoiTuongNghiepVuID"] = vatTuHangHoa.DoiTuongNghiepVu.ID;
                    else
                        addedRow["DoiTuongNghiepVuID"] = Guid.Empty;
                    addedRow["SoLuongTon"] = tonKho.SoLuong;
                    addedRow["GiaTriTongTon"] = tonKho.SoLuong * donGiaVon;
                    addedRow["GiaTriTongTonGiaBia"] = tonKho.SoLuong * vatTuHangHoa.GiaBia;

                    dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Rows.Add(addedRow);
                }

                count = 0;

                //Những hàng chưa xác định NCC cho vào 1 nhà Không xác định
                object soLuong, giaBia, giaVon;
                soLuong = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(SoLuongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", Guid.Empty));
                giaVon = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", Guid.Empty));
                giaBia = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTonGiaBia)", string.Format("DoiTuongNghiepVuID = '{0}'", Guid.Empty));

                DataRow addedRowEmpty = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.NewRow();

                addedRowEmpty["MaNCC"] = "";
                addedRowEmpty["TenNCC"] = "Không xác định";
                if (soLuong is decimal && (decimal)soLuong > 0)
                {
                    if (soLuong is decimal)
                        addedRowEmpty["SoLuong"] = Math.Round((decimal)soLuong, 0);
                    if (giaBia is decimal)
                        addedRowEmpty["GiaBia"] = Math.Round((decimal)giaBia, 0);
                    if (giaVon is decimal)
                        addedRowEmpty["GiaVon"] = Math.Round((decimal)giaVon, 0);
                }
                dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Rows.Add(addedRowEmpty);

                //Tính cho các nhà khác
                foreach (DataRow row in dsThongKeTonTheoNhaCungCap.DoiTuongNghiepVu.Rows)
                {
                    if (row["Choose"] is bool && (bool)row["Choose"] == true)
                    {
                        BasicForms.FrmProgressBar.Status = string.Format("Đã tính toán được {0} / {1} nhà cung cấp", count, total);

                        if (row["Choose"] is bool && (bool)row["Choose"])
                        {
                            Guid dtnvID = (Guid)row["ID"];
                            DoiTuongNghiepVu doiTuongNghiepVu = DanhMucDoiTuongNghiepVu.Instance.GetByID(dtnvID);

                            soLuong = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(SoLuongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));
                            giaVon = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTon)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));
                            giaBia = dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap.Compute("Sum(GiaTriTongTonGiaBia)", string.Format("DoiTuongNghiepVuID = '{0}'", dtnvID));

                            DataRow addedRow = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.NewRow();

                            addedRow["MaNCC"] = doiTuongNghiepVu.Ma;
                            addedRow["TenNCC"] = doiTuongNghiepVu.Ten;
                            if (soLuong is decimal && (decimal)soLuong > 0)
                            {
                                if (soLuong is decimal)
                                    addedRow["SoLuong"] = Math.Round((decimal)soLuong, 0);
                                if (giaBia is decimal)
                                    addedRow["GiaBia"] = Math.Round((decimal)giaBia, 0);
                                if (giaVon is decimal)
                                    addedRow["GiaVon"] = Math.Round((decimal)giaVon, 0);
                            }

                            dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap.Rows.Add(addedRow);
                            count++;
                        }
                    }
                }
                //ExportToExcel.ExportDataToExcel(dsThongKeTonTheoNhaCungCap.Detail_TonTheoNhaCungCap);

                gridControlTienTheoNCC.DataSource = dsThongKeTonTheoNhaCungCap.Detail_TongHopTienTheoNhaCungCap;
                FormatNumberInGridView(gridViewTienTheoNCC);
                FormatNumberInGridView(gridViewDsDoiTac);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                con.Close();
                con = null;
                BasicForms.FrmProgressBar.FinishShowProgress();
            }
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            PrintWithHeaderAndFooter(false, gridControlTienTheoNCC, true, true, "Báo cáo tổng hợp tiền hàng theo NCC", "", "", "", "");
        }

        private void cmbKyBaoCao_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                FrmThamSoBaoCao.ThietLapKhoangThoiGianBaoCao(cmbKyBaoCao.Text, cmbKyBaoCao, dtNgayBatDau, dtNgayKetThuc);
            }
            catch (Exception ex)
            {
                BasicForms.FrmExceptionNotifier.ShowAndLog(ex);
            }
        }

        private void chkShowHangDaCoGiaoDich_CheckedChanged(object sender, EventArgs e)
        {
            //Nếu Chọn hiện tất các mặt hàng thì không xem theo kho được
            //Vì hàng hóa chưa có mua bán nào thì không có ở kho nào cả
            if (chkShowHangDaCoGiaoDich.Checked)
            {
                cmbKho.Visible = true;
                lblTheoKho.Visible = true;
            }
            else
            {
                cmbKho.EditValue = Guid.Empty;
                cmbKho.Visible = false;
                lblTheoKho.Visible = false;
            }
        }
    }
}

